import {
  ModalForm,
  ProFormText,
  ProFormDatePicker,
} from '@ant-design/pro-components';
import { Form, message, } from 'antd';
import { request } from '../../utils/request.ts';
import { useEffect } from 'react';

const Edit = ({ open, setOpen, actionRef, record, }) => {
  const [form] = Form.useForm();

  useEffect(() => {
    if (open) {
      const initial = {
        ...record,
      };
      form.setFieldsValue(initial);
    }
  }, [open, record, form]);

  return (
    <>
      <ModalForm
        title={record?.id ? "编辑班级" : "新建班级"}
        form={form}
        autoFocusFirstInput
        open={open}
        width={500}
        layout="horizontal" // 关键点
        labelCol={{ span: 6 }} // label 占 6/24
        wrapperCol={{ span: 18 }} // 输入框占 18/24
        modalProps={{
          destroyOnClose: true,
          onCancel: () => setOpen(false),
        }}
        onFinish={async (values) => {
          const { ...other } = values;
          try {
            const res = await request(record?.id ? '/api/class/update' : '/api/class/save', {
              method: 'POST',
              data: {
                ...other,
                id: record?.id,
              },
            });
            if (res.data) {
              message.success('提交成功');
              setOpen(false);
              actionRef.current?.reload();
            } else {
              message.error(res.msg);
            }
          } catch (error) {
            console.error('Failed to submit data:', error);
          }
          return true;
        }}
      >
        <ProFormText
          name="name"
          label="班级名称"
          rules={[{ required: true, }]}
        />
        <ProFormText
          name="remark"
          label="标签"
          rules={[{ required: true, }]}
        />
        <ProFormDatePicker name="birthday" label="毕业日期" rules={[{ required: true, }]} />
      </ModalForm >
    </>
  );
};
export default Edit;